分类
联系方式
  1. 新浪微博
  2. E-mail

Flutter AndroidSurfaceGL

介绍

该类是 Flutter 在图形绘制底层的 Surface 封装,这一层比 Skia/OpenGL 还要底层,直接对接的是 EGL,EGL 是由平台提供的底层图形接口。

属性

该类有3个核心属性:

属性 类型 作用
native_window_ fml::RefPtr<AndroidNativeWindow> 对应于 Java 中的 Surface
onscreen_surface_ std::unique_ptr<AndroidEGLSurface> 屏幕绘制的 surface
offscreen_surface_ std::unique_ptr<AndroidEGLSurface> 用于 IO 线程纹理解析

onscreen_surface_ 创建

最典型的场景是,当 Java 侧 Surface 创建出来之后,会传入 C/C++ 层,转为 NDK 中的等效类 AndroidNativeWindow,通过层层转换,会进入 AndroidSurfaceGL::SetNativeWindow:

bool AndroidSurfaceGL::SetNativeWindow(
    fml::RefPtr<AndroidNativeWindow> window) {
  native_window_ = window;
  // Ensure the destructor is called since it destroys the `EGLSurface` before
  // creating a new onscreen surface.
  onscreen_surface_ = nullptr;
  // Create the onscreen surface.
  onscreen_surface_ = GLContextPtr()->CreateOnscreenSurface(window);
  if (!onscreen_surface_->IsValid()) {
    return false;
  }
  return true;
}

可以看到,onscreen_surface_ 实际上是由 AndroidContextGL::CreateOnscreenSurface 创建的:

std::unique_ptr<AndroidEGLSurface> AndroidContextGL::CreateOnscreenSurface(
    fml::RefPtr<AndroidNativeWindow> window) const {
  if (window->IsFakeWindow()) {
    return CreatePbufferSurface();
  } else {
    EGLDisplay display = environment_->Display();

    const EGLint attribs[] = {EGL_NONE};

    EGLSurface surface = eglCreateWindowSurface(
        display, config_,
        reinterpret_cast<EGLNativeWindowType>(window->handle()), attribs);
    return std::make_unique<AndroidEGLSurface>(surface, display, context_);
  }
}

其中都是 EGL 方法调用,最核心的是 eglCreateWindowSurface,把 window 传入进去,得到一个 EGLSurface,封装成一个 AndroidEGLSurface 返回。

这样 onscreen_surface_ 就代表了 Java 侧 Surface 的内容,onscreen_surface_ 就是实际显示内容的 framebuffer,Flutter 的内容绘制,都是往 onscreen_surface_ 里面进行绘制。